package com.zjf.carpark.controller;


import com.zjf.carpark.annotation.MyLogAnno;
import com.zjf.carpark.entities.User;
import com.zjf.carpark.service.impl.UserServiceImpl;
import com.zjf.carpark.utils.FileUploadUtil;
import com.zjf.carpark.utils.MD5Util;
import com.zjf.carpark.utils.RandomValidateCode;
import com.zjf.carpark.utils.ResponseData;
import com.zjf.carpark.vo.UserPageVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.zjf.carpark.utils.CodeAndMessage.*;

@CrossOrigin
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    ResponseData responseData;

    /**
     * 获取生成验证码显示到 UI 界面
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        //设置相应类型,告诉浏览器输出的内容为图片
        response.setContentType("image/jpeg");

        //设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);

        RandomValidateCode randomValidateCode = new RandomValidateCode();
        try {
            randomValidateCode.getRandcode(request, response);//输出图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户登录验证
     *
     * @param
     * @return
     */
    @MyLogAnno(value = "登录系统")
    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData login(@RequestBody Map<String, String> data, HttpServletRequest request) {
        // 获取验证码
        String randomcode_key = (String) request.getSession().getAttribute("randomcode_key");
        System.out.println(randomcode_key);
        String code = data.get("code");
        String userPwd = data.get("userPwd");
        // 密码两次加密
        String firstMD5 = MD5Util.md5(userPwd);
        String secondMD5 = MD5Util.twoMd5Pwd(firstMD5, salt);
        User user = new User();
        user.setUserName(data.get("userName"));
        user.setUserPwd(secondMD5);
        User loginUser = userService.login(user);

        // 是否存在用户
        if (loginUser != null) {
            // 验证码是否正确
            if (code != null && code.equalsIgnoreCase(randomcode_key)) {
                // 用户是否可用
                if (loginUser.getFlag()) {
                    System.out.println(request.getSession().getId());
                    request.getSession().setAttribute("user", loginUser);
                    responseData = new ResponseData(CODE200, SUCCESS);
                    responseData.putDataValue("roleId", loginUser.getRoleId());
                    responseData.putDataValue("userId", loginUser.getUserId());
                } else {
                    responseData = new ResponseData(808, "用户暂时不可用");
                }
            } else {
                responseData = new ResponseData(CHECKCODE, CHECKCODEERROR);
            }
        } else {
            responseData = new ResponseData(CODE0, ERROR);
        }
        return responseData;
    }

    /**
     * 退出系统
     *
     * @param request
     * @return
     */
    @MyLogAnno(value = "退出系统")
    @RequestMapping(value = "/exit")
    @ResponseBody
    public ResponseData exit(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        responseData = new ResponseData(CODE200, SUCCESS);
        return responseData;
    }

    /**
     * 用户列表
     *
     * @param userPageVo
     * @return
     */
    @RequestMapping(value = "/userList")
    @ResponseBody
    public ResponseData userList(UserPageVO userPageVo) {
        if ("".equals(userPageVo.getUserName())) {
            userPageVo.setUserName(null);
        }
        if ("".equals(userPageVo.getUserTel())) {
            userPageVo.setUserTel(null);
        }
        List<User> list = userService.showByMsg(userPageVo);
        int totalCount = userService.totalCount(userPageVo);
        if (list != null) {
            responseData = new ResponseData(CODE200, SUCCESS);
            responseData.putDataValue("userList", list);
            responseData.setCount(totalCount);
        } else {
            responseData = new ResponseData(CODE0, ERROR);
        }
        return responseData;
    }

    /**
     * 用户删除
     */
    @MyLogAnno(value = "用户删除")
    @RequestMapping(value = "/deleteUser")
    @ResponseBody
    public ResponseData deleteUser(@RequestBody Map<String, Integer> data) {
        Integer userId = data.get("userId");
        int result = userService.deleteById(userId);
        if (result != 0) {
            responseData = new ResponseData(CODE200, SUCCESS);
        } else {
            responseData = new ResponseData(CODE0, ERROR);
        }
        return responseData;
    }

    /**
     * 用户修改
     */
    @MyLogAnno("修改用户")
    @RequestMapping(value = "/updateUser")
    @ResponseBody
    public ResponseData updateUser(User user) {

        int result = userService.update(user);
        if (result != 0) {
            responseData = new ResponseData(CODE200, SUCCESS);
        } else {
            responseData = new ResponseData(CODE0, ERROR);
        }
        return responseData;
    }

    /**
     * 通过用户id查找一个用户
     */
    @RequestMapping(value = "/selectById")
    @ResponseBody
    public ResponseData selectById(@RequestBody Map<String, Integer> data) {
        Integer userId = data.get("userId");
        User user = userService.selectById(userId);
        if (user != null) {
            responseData = new ResponseData(CODE200, SUCCESS);
            responseData.putDataValue("user", user);
        } else {
            responseData = new ResponseData(CODE0, ERROR);
        }
        return responseData;
    }

    @RequestMapping(value = "/addUser")
    @ResponseBody
    @MyLogAnno("添加新用户")
    public ResponseData addUser(User user) {
        //判断用户昵称是否存在
        int isExist = userService.selectByName(user.getUserName());
        String firstMD5 = MD5Util.md5(user.getUserPwd());
        String secondMD5 = MD5Util.twoMd5Pwd(firstMD5, salt);
        user.setUserPwd(secondMD5);
        //不存在则新增
        if (isExist == 0) {
            int result = userService.save(user);
            if (result != 0) {
                responseData = new ResponseData(CODE200, SUCCESS);
            } else {
                responseData = new ResponseData(CODE0, ERROR);
            }
        } else {
            responseData = new ResponseData(CODE403, EXIST);
        }
        return responseData;
    }

    /**
     * 图片上传
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    @ResponseBody
    @MyLogAnno(value = "上传图片")
    public ResponseData test(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        responseData = new ResponseData();
        responseData = FileUploadUtil.fileUpload(file, "imgs/user", request);
        return responseData;
    }
}
